package com.venusj.ipersistence.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.jboss.C3P0PooledDataSource;
import com.venusj.ipersistence.io.Resources;
import com.venusj.ipersistence.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author zhangjh
 * @date 2020/10/15
 * @desc
 */
public class XmlConfigBuilder {

    private Configuration configuration;


    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }


    /**
     * 将配置文件解析封装城Configuration对象
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : selectNodes) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        this.configuration.setDataSource(comboPooledDataSource);


        List<Element> mappers = rootElement.selectNodes("//mapper");
        for (Element element: mappers) {
            String resource = element.attributeValue("resource");
            InputStream mapperInStream = Resources.getResourceAsStream(resource);
            // 解析mapper.xml文件
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(this.configuration);
            xmlMapperBuilder.parse(mapperInStream);
        }

        return this.configuration;
    }
}
